package com.wectrls.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Set;

/**
 * @author chenjian
 * @Package
 * @Description: 数据变更工具类
 * @date 2019/7/5 19:36
 */
public class ObjChangeUtils {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static String getChanged(Object bef, Object aft) throws IllegalAccessException, JsonProcessingException {
        HashMap<String, String> map = Maps.newHashMap();
        Class<?> befClass = bef.getClass();
        Class<?> aftClass = aft.getClass();
        Field[] befFields = befClass.getDeclaredFields();
        Field[] aftFields = aftClass.getDeclaredFields();
        boolean equals = Arrays.equals(befFields, aftFields);
        if (equals) {
            HashMap<String, String> befMap = getMap(bef, befFields);
            HashMap<String, String> aftMap = getMap(aft, aftFields);
            Set<String> names = befMap.keySet();
            for (String name : names) {
                String befv = befMap.get(name);
                String aftv = aftMap.get(name);
                if (!befv.equals(aftv)) {
                    map.put(name, befv.substring(1, befv.length() - 1) + "-" + aftv.substring(1, aftv.length() - 1));
                }
            }
        }
        return objectMapper.writeValueAsString(map);
    }

    private static HashMap<String, String> getMap(Object bef, Field[] befFields) throws JsonProcessingException, IllegalAccessException {
        HashMap<String, String> befMap = Maps.newHashMap();
        for (Field field : befFields) {
            field.setAccessible(true);
            String name = field.getName();
            String value = objectMapper.writeValueAsString(field.get(bef));
            befMap.put(name, value);
        }
        return befMap;
    }
}
